package com.block.product.service.union;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import com.block.product.service.utils.YinDianUtils;
import com.market.member.service.IMemberSourceInfoService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class YinDianUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();

    @Autowired
    private MemberSourceInfoMapper memberSourceInfoMapper;

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) throws Exception {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(true);
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) throws Exception {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String apiSecret = apiInfoParam.getApiSecret();
        String apiCode = apiInfoParam.getApiCode();
        String mobile = uniLoginDTO.getMobile();
        String mobileMd5 = SecureUtil.md5(mobile).toLowerCase();
        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectByMobileMd5(mobileMd5);

        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("mobile", mobile);
        bizmMap.put("name", memberSourceInfo.getRealname());
        bizmMap.put("sex", memberSourceInfo.getSex());
        bizmMap.put("age", memberSourceInfo.getAge());
        bizmMap.put("loanAmount", YinDianUtils.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizmMap.put("loanTime", YinDianUtils.getLoanTime(memberSourceInfo.getLoanTime()));
        bizmMap.put("province", memberSourceInfo.getProvince());
        bizmMap.put("city", memberSourceInfo.getCity());
        Integer job = YinDianUtils.getJob(memberSourceInfo.getGongzuo());
        bizmMap.put("job", job);
        bizmMap.put("salaryPay", YinDianUtils.getSalaryPay(memberSourceInfo.getShouru()));
        if(job == 2){
            bizmMap.put("businessLicense",2);
        }else {
            bizmMap.put("businessLicense",1);
        }
        bizmMap.put("house", YinDianUtils.getHouse(memberSourceInfo.getHouse()));
        bizmMap.put("car", YinDianUtils.getCar(memberSourceInfo.getCar()));
        bizmMap.put("socialInsurance", YinDianUtils.getSheBao(memberSourceInfo.getShebao()));
        bizmMap.put("accumulationFund", YinDianUtils.getGjj(memberSourceInfo.getGjj()));
        bizmMap.put("insurance", YinDianUtils.getBaoXian(memberSourceInfo.getBaoxian()));
        bizmMap.put("sesame", YinDianUtils.getZhiMa(memberSourceInfo.getZhima()));
        bizmMap.put("overdue", YinDianUtils.getYuQi(memberSourceInfo.getYuqi()));


        String encrypt = encrypt(JSON.toJSONString(bizmMap), apiSecret);
        Long timestamp = Long.valueOf(System.currentTimeMillis());

        String s1 ="body="+ encrypt + "&org=" + apiCode + "&timestamp=" +timestamp+"&secret="+apiSecret;
        String sign = SecureUtil.md5(s1).toLowerCase();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("body", encrypt);
        paramMap.put("org", apiCode);
        paramMap.put("sign", sign);
        paramMap.put("timestamp", timestamp);


        log.info("【金穗花分期】联登开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl).header("Content-Type", "application/json").body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【金穗花分期】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer respCode = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        JSONObject data = resultObject.getJSONObject("data");


        loginResult.setCode(respCode.toString());
        loginResult.setMessage(msg);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));
        if (StrUtil.equals(respCode.toString(), "200")) {
            Integer status = data.getInteger("status");
            if(StrUtil.equals(status.toString(), "1")){
                String url = data.getString("link");
                loginResult.setLoginUrl(url);
                loginResult.setSuccess(true);
            }
        }
        return loginResult;
    }

    public static String encrypt(String content, String key) throws Exception
    {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes,
                "AES"));
        byte[] bytes =
                cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(bytes);
    }



}
